package cn.skyclass.controls
{
	import flash.display.Sprite;
	
	import mx.controls.ProgressBar;
	import mx.core.Application;
	import mx.managers.CursorManager;
	import mx.managers.PopUpManager;
	
	/**
	 * 弹出用户等待框
	 * @author fl
	 */	
	public class WaitingDialog
	{
		private static var instance:WaitingDialog;		
		public static function getInstance():WaitingDialog{
			if(instance == null){
				instance = new WaitingDialog();
			}
			return instance;
		}

		/**
		 * 显示等待框的时候是否将鼠标置为忙碌状态（时钟图示）
		 */
		public var showBusyCursor:Boolean = true;
				
		protected var progress:ProgressBar = null;
		protected var msgStack:Array = new Array();
		protected var popCount:int = 0;
		protected var defaultMsg:String = "Please wait ...";
		
		/**
		 * 设置自定义的进度栏
		 * @param bar
		 */		
		public function setProgressBar(bar:ProgressBar):void{
			this.progress = bar;
		}
		
		/**
		 * 显示等待框
		 * @param msg 需要显示的信息
		 * @param modal 是否作为模态窗口弹出
		 */				
		public function beginWaiting(msg:String="", modal:Boolean=true):void{
			if(!progress){
				progress = getNewProgressBar();
			}
			
			msgStack.push(progress.label);
			progress.label = msg ? msg : defaultMsg;
			
			if(popCount == 0){
				PopUpManager.addPopUp(progress, Application.application as Sprite, modal);
				PopUpManager.centerPopUp(progress);
			}
			
			popCount++;
			
			if(this.showBusyCursor){
				CursorManager.setBusyCursor();
			}
		}
		
		/**
		 * 关闭等待框
		 */		
		public function endWaiting():void{
			if(popCount > 0){
				popCount--;
			}
			
			if(popCount == 0){
				PopUpManager.removePopUp(progress);
			}

			if(msgStack.length > 0){
				progress.label = msgStack.pop().toString();
			}else{
				progress.label = defaultMsg;
			}
			
			if(this.showBusyCursor){
				CursorManager.removeBusyCursor();
			}				
		}
		
		protected function getNewProgressBar():ProgressBar{
			var p:ProgressBar = new ProgressBar();
			p.width = 250;
			p.indeterminate = true;
			p.labelPlacement = "center";
			p.setStyle("barColor", "#E8E060");
			return p;		
		}
		
	}
}